#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUF_SIZE 30

int main(int argc,char *argv[])
{
    int sock;
    char message[BUF_SIZE];
    size_t str_len;
    //socklen_t addr_size;
    struct sockaddr_in serv_addr; //,from_addr;

    sock = socket(AF_INET, SOCK_DGRAM, 0);
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = PF_INET;
    serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
    serv_addr.sin_port = htons((uint16_t)atoi(argv[2]));
    connect(sock, (const struct sockaddr *)&serv_addr, sizeof(serv_addr));

    while(1) {
        fputs("输入消息：", stdout);
        fgets(message, sizeof(message), stdin);
        if(!strcmp(message, "q\n")) {
            break;
        }

        //sendto(sock, message, strlen(message), 0, (const struct sockaddr *)&serv_addr, sizeof(serv_addr));
        //addr_size = sizeof(from_addr);
        //str_len = (size_t)recvfrom(sock, message, BUF_SIZE, 0, (struct sockaddr *)&from_addr, &addr_size);

        write(sock, message, strlen(message));
        str_len = (size_t)read(sock, message, sizeof(message) - 1);
        message[str_len]=0;

        printf("服务器传回的消息: %s", message);
    }

    close(sock);
    return 0;
}

